home *** CD-ROM | disk | FTP | other *** search
- Path: sun001.spd.dsccc.com!spd!jmccarty
- From: jmccarty@spd.dsccc.com (Mike McCarty)
- Newsgroups: comp.lang.c
- Subject: Re: volatile type
- Date: 14 Feb 1996 19:30:51 GMT
- Organization: DSC Communications Corporation, Plano, Texas USA
- Message-ID: <4ftd9b$as2@sun001.spd.dsccc.com>
- References: <4fro3j$jbi@service.polymtl.ca>
- NNTP-Posting-Host: aplo139.spd.dsccc.com
-
- In article <4fro3j$jbi@service.polymtl.ca>,
- Yannick Heneault <fermi@info.polymtl.ca> wrote:
- )Can someone know information about this data type. A example is
- )welcome!
-
- "volatile" is not a type. It is a storage class. It ranks with "static"
- in this respect. What it means to the compiler is that certain
- optimizations cannot be performed on this variable. Specifically, any
- optimizations which depend on the variable retaining its value between
- accesses is prohibited.
-
- As an example of the type of optimization prohibited: (C source and
- output assembler)
-
-
- if (x < 0) y = x;
-
- load x
- compare 0
- jump greater_or_equal,around
-
- load x
- store y
- around:
-
- Many compilers would remove the second load of x, since the value of x
- is already in the processor. This optimization depends on x not changing
- values between accesses.
-
- As an example of the intended use, consider a "variable" which is
- actually a memory mapped I/O port, say for a serial device. When looking
- for a character from the serial port, one reads the status register and
- looks for some bit turned on (or off) to indicate that a character is
- available for read.
-
- char serial_get_char() {
- unsigned char *status = SERIAL_DEVICE_STATUS_ADDRESS,
- *data = SERIAL_DEVICE_DATA_ADDRESS;
-
- while ((*status & CHAR_AVAILABLE) == 0)
- ;
- return *data;
- }
-
- The generated code might look like this:
-
- load [status]
- and 0x20
- jump not_zero,label_1000
- label_1001:
- jump label_1001
- label_1000:
- load [data]
- return
-
- The compiler has noticed that the load and compare are loop invariant
- and moved them outside the loop. By specifying "volatile", for the
- variable "status", the user forces the compiler to consider the
- variable might change between reads. Thus "label_1001" would be placed
- -before- the load from status, since its value is no longer loop invariant.
-
- Another place where one might use this is where another context (task
- or interrupt, etc) might modify the variable.
-
- Mike
- ----
- char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}
-
- I don't speak for DSC. <- They make me say that.
-